﻿Imports System.IO
Imports System.Collections.Generic
Imports System.Net.WebRequestMethods.Ftp
Imports System.Net

Public Class upload
    Public MainForm As Form1
    Private Sub FlowLayoutPanel1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles FlowLayoutPanel1.MouseDoubleClick
        Try

        
        Dim openfiledialog1 As New OpenFileDialog
        openfiledialog1.Title = "PDF Files"
        openfiledialog1.Multiselect = True
        openfiledialog1.Filter = "PDF Files (*.pdf) |*.pdf"
        If openfiledialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            color1 = 1
            For Each items In openfiledialog1.FileNames
                Dim info As New FileInfo(items)
                Dim newitem As New additem
                For Each ItemPanel As additem In Me.FlowLayoutPanel1.Controls
                    If ItemPanel.FileInformation.Name = info.Name Then
                        GoTo nextitem
                    End If
                Next
                newitem.uploadform = Me
                newitem.FileInformation = info
                    'load vendor
                    If (MainForm.AutoCompleteCollectionVendor.Count <> 0) Then
                        newitem.selectvendor.AutoCompleteCustomSource = MainForm.AutoCompleteCollectionVendor
                    End If
                       FlowLayoutPanel1.Controls.Add(newitem)
                ChangeColor()
nextitem:
            Next

            End If
        Catch ex As Exception

        End Try
    End Sub



    Private Sub FlowLayoutPanel1_DragDrop(sender As Object, e As DragEventArgs) Handles FlowLayoutPanel1.DragDrop, MyBase.DragDrop
        If e.Data.GetDataPresent("FileDrop", True) = True Then

            Dim Files() As String
            Dim i As Integer

            Files = e.Data.GetData(DataFormats.FileDrop)
            color1 = 1

            For i = 0 To Files.Length - 1
                'FileList.Items.Add(Files(i))
                Dim newitem As New additem
                Dim info As New FileInfo(Files(i))
                If info.Extension <> Nothing And info.Extension = ".pdf" Then
                    For Each ItemPanel As additem In Me.FlowLayoutPanel1.Controls
                        If ItemPanel.FileInformation.Name = info.Name Then
                            GoTo nextitem
                        End If
                    Next
                    newitem.uploadform = Me
                    newitem.FileInformation = info
                    If (MainForm.AutoCompleteCollectionVendor.Count <> 0) Then
                        newitem.selectvendor.AutoCompleteCustomSource = MainForm.AutoCompleteCollectionVendor
                    End If
                    FlowLayoutPanel1.Controls.Add(newitem)
                    ChangeColor()
                End If
nextitem:
            Next

        End If
    End Sub
    Private Sub Main_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles Me.DragEnter, FlowLayoutPanel1.DragEnter
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            e.Effect = DragDropEffects.All
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Hide()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        'Checking

        For Each ItemPanel As additem In Me.FlowLayoutPanel1.Controls
            If ItemPanel.selectvendor.Text = "" Then
                MsgBox("Invalid Document Name")
                ItemPanel.selectvendor.Focus()
                Return
            End If
            If ItemPanel.ComboBox1.Text = "" Then
                MsgBox("Invalid Document Type")
                ItemPanel.ComboBox1.Focus()
                Return
            End If
            If ItemPanel.selectvendor.Text = "" Then
                MsgBox("Invalid Vendor")
                ItemPanel.selectvendor.Focus()
                Return
            End If
        Next


        For Each ItemPanel As additem In Me.FlowLayoutPanel1.Controls
            Dim t As New Threading.Thread(AddressOf savefile)
            t.Start(ItemPanel)
        Next

        'Dim filename As String = "C:\Users\sergentlois\Desktop\NULL and Nothing.pdf"
        'If File.Exists(filename) = True Then
        '    ftpupload(filename, "sample.pdf")
        'Else
        '    MsgBox("no file exists")
        'End If
    End Sub

    Function savefile(usercntrl As additem) As Boolean
        SyncLock Me
            usercntrl.txtstats.Text = "Uploading.."
            Dim genint As Integer
            Dim rand As New Random
            genint = rand.Next(10000, 99999)
            usercntrl.status.CheckState = CheckState.Indeterminate

            Dim company, dept, owner, vendor, title, docutype, dateissue, originalfilename, serverfilename, description1, description2, description3, Reference1, Reference2, CheckNumber As String
            company = My.Settings.company.ToUpper
            dept = My.Settings.department
            owner = My.Settings.username.ToUpper
            vendor = usercntrl.selectvendor.Text.ToUpper
            title = usercntrl.txttitle.Text.ToLower
            docutype = usercntrl.ComboBox1.Text
            dateissue = usercntrl.DateTimePicker1.Value.ToString.ToLower
            description1 = usercntrl.TextBox1.Text
            Reference1 = usercntrl.txtref1.Text
            Reference2 = usercntrl.txtref2.Text
            CheckNumber = usercntrl.check1.Text

            originalfilename = usercntrl.FileInformation.FullName.Replace("\", "\/")
            serverfilename = My.Settings.fileprotocol & My.Settings.department & "/" & genint.ToString & "_" & usercntrl.FileInformation.Name
            Dim sqlcommand As String

            sqlcommand = "INSERT INTO `records` (`company`,`Department`,`owner`, `vendor`, `title`, `docutype`, `dateissue`, `originalfilename`, `serverfilename`, `description1`, `description2`, `description3`,`Reference1`, `Reference2`, `CheckNumber`) VALUES ('" & company & "','" & dept & "','" & owner & "','" & vendor.ToUpper & "','" & title & "','" & docutype & "','" & dateissue & "','" & originalfilename & "','" & serverfilename & "','" & description1 & "','" & description2 & "','" & description3 & "','" & Reference1 & "','" & Reference2 & "','" & CheckNumber & "')"

            Dim con As New Odbc.OdbcConnection
            con.ConnectionString = My.Settings.con
            Dim cmd As New Odbc.OdbcCommand(sqlcommand, con)
            Try
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            Catch ex As Exception
                MsgBox(ex.Message)
                usercntrl.status.CheckState = CheckState.Unchecked
                Return False
            End Try
            Try
                ftpupload(usercntrl.FileInformation.FullName, serverfilename)
                usercntrl.status.Visible = True
                usercntrl.status.Checked = False
                usercntrl.status.Text = "Success"
            Catch ex As Exception
                'MsgBox(ex.Message)
                usercntrl.status.CheckState = CheckState.Unchecked
                Return False
            End Try
            usercntrl.status.CheckState = CheckState.Checked
            usercntrl.Dispose()
            usercntrl.txtstats.Text = "Success"
            'Addvendor
            Dim AddVend As New Threading.Thread(AddressOf AddNewVendor)
            AddVend.Start(vendor)
            Return True
        End SyncLock

    End Function

    Sub AddNewVendor(Vendor As String)
        'Check Duplicate

        Vendor = Vendor.ToUpper
        Dim sqlcommand As String = ""
        Dim Duplicate As Boolean = False

        Dim con As New Odbc.OdbcConnection
        Dim reader As Odbc.OdbcDataReader
        con.ConnectionString = My.Settings.con
        Try
            sqlcommand = "SELECT `vendor` FROM `vendors` WHERE `vendor` = '" & Vendor & "';"
            Dim cmd As New Odbc.OdbcCommand(sqlcommand, con)
            con.Open()
            reader = cmd.ExecuteReader()
            While reader.Read()
                If reader(0) <> Nothing Then
                    Duplicate = True
                    Exit Sub
                End If
            End While
        Catch ex As Exception

        End Try

        'Add INSERT INTO `vendors`(`vendorid`, `vendor`, `company`) VALUES ([value-1],[value-2],[value-3])
        Try
            If Duplicate = False Then
                sqlcommand = "INSERT INTO `vendors`(`vendorid`, `vendor`, `company`) VALUES ('','" & Vendor & "','" & My.Settings.company.ToUpper & "');"
                Dim cmd As New Odbc.OdbcCommand(sqlcommand, con)
                cmd.ExecuteNonQuery()
            End If
        Catch ex As Exception

        End Try
        
        con.Close()
    End Sub
    Sub ftpupload(localfilename As String, ftpfilename As String)
        ' set up request...
        Dim clsRequest As System.Net.FtpWebRequest = DirectCast(System.Net.WebRequest.Create(ftpfilename), System.Net.FtpWebRequest)
        clsRequest.Credentials = New System.Net.NetworkCredential(My.Settings.ftpusername, My.Settings.ftppassword)
        clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
        clsRequest.Proxy = Nothing

        ' read in file...
        Dim bFile() As Byte = System.IO.File.ReadAllBytes(localfilename)

        ' upload file...
        Dim clsStream As System.IO.Stream = clsRequest.GetRequestStream()
        clsStream.Write(bFile, 0, bFile.Length)
        clsStream.Close()
        clsStream.Dispose()

    End Sub
   
   
    Private Sub upload_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        CheckForIllegalCrossThreadCalls = False
    End Sub
    Public color1 As Integer = 1
    Public Sub ChangeColor()
        Try
            For Each item In FlowLayoutPanel1.Controls
                If color1 = 1 Then
                    color1 = 0
                    item.BackColor = Color.WhiteSmoke
                ElseIf color1 = 0 Then
                    color1 = 1
                    item.BackColor = Color.Gainsboro
                End If
            Next
        Catch ex As Exception

        End Try
    End Sub
    Private Sub Button3_Click(sender As Object, e As EventArgs)

    End Sub

    Private Sub Button3_Click_1(sender As Object, e As EventArgs) Handles Button3.Click
        Try

        
        Dim openfiledialog1 As New OpenFileDialog
        openfiledialog1.Title = "PDF Files"
        openfiledialog1.Multiselect = True
        openfiledialog1.Filter = "PDF Files (*.pdf) |*.pdf"
        If openfiledialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            color1 = 1
            For Each items In openfiledialog1.FileNames
                Dim info As New FileInfo(items)
                Dim newitem As New additem
                For Each ItemPanel As additem In Me.FlowLayoutPanel1.Controls
                    If ItemPanel.FileInformation.Name = info.Name Then
                        GoTo nextitem
                    End If
                Next
                newitem.uploadform = Me
                newitem.FileInformation = info
                    'load vendor
                    If (MainForm.AutoCompleteCollectionVendor.Count <> 0) Then
                        newitem.selectvendor.AutoCompleteCustomSource = MainForm.AutoCompleteCollectionVendor
                    End If
                    If MainForm.Doctypes.Count <> 0 Then
                        For Each itm In MainForm.Doctypes
                            newitem.ComboBox1.Items.Add(itm)
                        Next

                    End If
                    FlowLayoutPanel1.Controls.Add(newitem)
                    ChangeColor()
nextitem:
                Next

            End If
        Catch ex As Exception

        End Try
    End Sub

    
End Class